import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:get/get.dart'; // 引入 GetX

class UserInfo {
  // 1. 将 language 改为 RxString 类型，默认值设为字符串（如"zh"表示中文）
  final RxInt _id = 0.obs;
  final RxString _nickname = "".obs;
  final RxString _avatar = "".obs;
  final RxInt _coin = 0.obs;
  final RxString _language = "en".obs; // 改为字符串类型，默认中文
  final RxInt _countryCode = 1.obs;
  final RxInt _isAutoBuy = 0.obs;
  final RxInt _loginType = 0.obs; // 0 为游客，非0为绑定登录
  final RxString _token = "".obs;
  final RxString _vipExpireTime = "".obs; // VIP过期时间
  final RxString _deviceId = "".obs; // device ID属性

  // 单例实例
  static final UserInfo _instance = UserInfo._internal();

  // 工厂构造函数，返回单例
  factory UserInfo() {
    return _instance;
  }

  // 私有构造函数
  UserInfo._internal();

  // 从JSON初始化（更新响应式属性的值），调整language的类型处理
  UserInfo.fromJson(Map<String, dynamic> json) {
    _id.value = json['user_id'] ?? 0;
    _nickname.value = json['nickname'] ?? "";
    _avatar.value = json['avatar'] ?? "";
    _coin.value = json['coin'] ?? 0;
    // 处理language：如果后端返回int则转为对应字符串，否则直接取字符串
    if (json['language'] is int) {
      _language.value = (json['language'] ?? 1);
    } else {
      _language.value = json['language'] ?? "en";
    }
    _countryCode.value = json['country_code'] ?? 1;
    _isAutoBuy.value = json['is_auto_buy'] ?? 0;
    _loginType.value = json['login_type'] ?? 0;
    _token.value = json['token'] ?? "";
    _vipExpireTime.value = json['vip_expire_time'] ?? "";
    _deviceId.value = json['device_id'] ?? "";
  }

  // 2. Getter 和 Setter 调整为字符串类型
  int get id => _id.value;
  set id(int value) {
    _id.value = value;
    _autoSave();
  }

  String get nickname => _nickname.value;
  set nickname(String value) {
    _nickname.value = value;
    _autoSave();
  }

  String get avatar => _avatar.value;
  set avatar(String value) {
    _avatar.value = value;
    _autoSave();
  }

  int get coin => _coin.value;
  set coin(int value) {
    _coin.value = value;
    _autoSave();
  }

  // language 的 Getter 和 Setter 改为字符串类型
  String get language => _language.value;
  set language(String value) {
    _language.value = value;
    _autoSave();
  }

  int get countryCode => _countryCode.value;
  set countryCode(int value) {
    _countryCode.value = value;
    _autoSave();
  }

  ///是否自动购买
  int get isAutoBuy => _isAutoBuy.value;
  set isAutoBuy(int value) {
    _isAutoBuy.value = value;
    _autoSave();
  }

  int get loginType => _loginType.value;
  set loginType(int value) {
    _loginType.value = value;
    _autoSave();
  }

  String get token => _token.value;
  set token(String value) {
    _token.value = value;
    _autoSave();
  }

  String get vipExpireTime => _vipExpireTime.value;
  set vipExpireTime(String value) {
    _vipExpireTime.value = value;
    _autoSave();
  }

  String get deviceId => _deviceId.value;
  set deviceId(String value) {
    _deviceId.value = value;
    _autoSave();
  }

  // 转换为JSON（language 存储为字符串）
  Map<String, dynamic> toJson() {
    return {
      'user_id': _id.value,
      'nickname': _nickname.value,
      'avatar': _avatar.value,
      'coin': _coin.value,
      'language': _language.value, // 存储为字符串
      'country_code': _countryCode.value,
      'is_auto_buy': _isAutoBuy.value,
      'login_type': _loginType.value,
      'token': _token.value,
      'vip_expire_time': _vipExpireTime.value,
      'device_id': _deviceId.value,
    };
  }

  // 更新单例属性（调整language的赋值逻辑）
  void updateInfo(UserInfo newInfo) {
    _id.value = newInfo._id.value;
    _nickname.value = newInfo._nickname.value;
    _avatar.value = newInfo._avatar.value;
    _coin.value = newInfo._coin.value;
    _language.value = newInfo._language.value; // 字符串直接赋值
    _countryCode.value = newInfo._countryCode.value;
    _isAutoBuy.value = newInfo._isAutoBuy.value;
    _loginType.value = newInfo._loginType.value;
    _token.value = newInfo._token.value;
    _vipExpireTime.value = newInfo._vipExpireTime.value;
    _deviceId.value = newInfo._deviceId.value;
    _autoSave();
  }

  // 从JSON更新信息（处理language的类型兼容）
  void updateFromJson(Map<String, dynamic> json) {
    _id.value = json['user_id'] ?? _id.value;
    _nickname.value = json['nickname'] ?? _nickname.value;
    _avatar.value = json['avatar'] ?? _avatar.value;
    _coin.value = json['coin'] ?? _coin.value;

    // 兼容新旧格式：如果是int则转换为字符串，否则直接用字符串
    if (json['language'] != null) {
      if (json['language'] is int) {
        _language.value = (json['language']);
      } else {
        _language.value = json['language'].toString();
      }
    }

    _countryCode.value = json['country_code'] ?? _countryCode.value;
    _isAutoBuy.value = json['is_auto_buy'] ?? _isAutoBuy.value;
    _loginType.value = json['login_type'] ?? _loginType.value;
    _token.value = json['token'] ?? _token.value;
    _vipExpireTime.value = json['vip_expire_time'] ?? _vipExpireTime.value;
    _deviceId.value = json['device_id'] ?? _deviceId.value;
    _autoSave();
  }

  // 自动保存到本地存储
  Future<void> _autoSave() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('user_info', jsonEncode(toJson()));
  }

  // 从本地加载（处理language的字符串转换）
  Future<void> loadFromLocal() async {
    final prefs = await SharedPreferences.getInstance();
    final jsonString = prefs.getString('user_info');
    if (jsonString != null) {
      final jsonData = jsonDecode(jsonString);
      _id.value = jsonData['user_id'] ?? 0;
      _nickname.value = jsonData['nickname'] ?? "";
      _avatar.value = jsonData['avatar'] ?? "";
      _coin.value = jsonData['coin'] ?? 0;
      // 本地存储的language是字符串，直接赋值
      _language.value = jsonData['language'] ?? "zh";
      _countryCode.value = jsonData['country_code'] ?? 1;
      _isAutoBuy.value = jsonData['is_auto_buy'] ?? 0;
      _loginType.value = jsonData['login_type'] ?? 0;
      _token.value = jsonData['token'] ?? "";
      _vipExpireTime.value = jsonData['vip_expire_time'] ?? "";
      _deviceId.value = jsonData['device_id'] ?? "";
    }
  }

  // 退出登录，清空数据（language重置为默认字符串）
  Future<void> clearUserInfo() async {
    _id.value = 0;
    _nickname.value = "";
    _avatar.value = "";
    _coin.value = 0;
    _language.value = "zh"; // 重置为默认语言字符串
    _countryCode.value = 1;
    _isAutoBuy.value = 0;
    _loginType.value = 0;
    _token.value = "";
    _vipExpireTime.value = "";
    _deviceId.value = "";
    // 清除本地存储
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('user_info');
  }
}
